# 聊天机器人

import os

from fastapi import FastAPI
from langchain.chains.summarize.map_reduce_prompt import prompt_template
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
from langserve import add_routes, RemoteRunnable
from langchain_community.chat_message_histories import ChatMessageHistory

# langsmith 监控

os.environ['LANGCHAIN_TRACING_V2'] = "true"
os.environ['LANGCHAIN_API_KEY'] = '1123'

# 调用大模型

model = ChatOpenAI(model='gpt-4-turbo')

# msg = [
#     SystemMessage(content='请将以下的内容翻译成意大利语'),
#     HumanMessage(content='你好，请问你去哪里')
# ]

# result = model.invoke(msg)
# print(result)
#
# #简单解析响应数据
# parser =StrOutputParser()
#
# return_str=parser.invoke(result)
#
# print(return_str)

# 得到链,直接使用chain
# chain = model | parser
# print(chain.invoke(msg))
parser = StrOutputParser()
prompt_template = ChatPromptTemplate.from_messages([
    ('system', '你是一个乐于助人的助手，用{language}尽你所能回答所有问题'),
    MessagesPlaceholder(variable_name='my_msg')
])

chain = prompt_template | model

# 保存每次历史聊天记录ChatMessageHistory
store = {}  # 所有用户的聊天记录保存至store，key：sessionId，value：历史聊天记录


def get_session_history(session_id: str):
    if session_id not in store:
        store[session_id] = ChatMessageHistory()
    return store[session_id]


do_message = RunnableWithMessageHistory(
    chain,
    get_session_history,
    input_messages_key='my_msg'  # 每次聊天时候发送msg的key
)

config = {'configurable': {'session_id': 'zhangsan'}}

# 第一轮聊天
resp = do_message.invoke(
    {
        'my_msg': [HumanMessage(content='hello,i am lp')],
        'language': 'zh-CN',
    },
    config=config
)
print(resp.content)

# two time
resp2 = do_message.invoke(
    {
        'my_msg': [HumanMessage(content='hello, what is my name ')],
        'language': 'zh-CN',
    },
    config=config
)
print(resp2.content)

# third time
config = {'configurable': {'session_id': 'zhangsan1'}}
for resp in do_message.stream(
        {
            'my_msg': [HumanMessage(content='hello, please tell me a joke ')],
            'language': 'zh-CN',
        },
        config=config
):
    # 每一次resp都是一个token
    print(resp.content, end='-')
# 一个token一个-这样的输出


# print(chain.invoke({'language':'English','text':'不能去打球了'}))
